<template>
  <a-modal
    :title="title"
    :visible="visible"
    @cancel="visible = false"
    width="1200px"
  >
    <template slot="footer">
      <a-button type="primary" @click="visible = false">
        关闭
      </a-button>
    </template>
    <a-radio-group v-model="type" button-style="solid">
      <a-radio-button :value="0">当前单据流程</a-radio-button>
      <a-radio-button :value="1">历史单据流程</a-radio-button>
    </a-radio-group>

    <a-tabs type="card" class="mb20">
      <a-tab-pane key="1" tab="当前流程">
        <a-spin :spinning="spinning" style="margin: 0">
          <img style="width: 100%" :src="flowChart">
        </a-spin>
        <s-table
          ref="ApprovetableCurrent"
          bordered
          size="default"
          row-key="key"
          :columns="columnApproveCurrent"
          :data="loadDataCurrent"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :show-pagination="false"
        >
          <template slot="serial" slot-scope="text, record, index">{{ index + 1 }}</template>
        </s-table>
      </a-tab-pane>
      <a-tab-pane key="2" tab="历史流程">
        <s-table
          ref="Approvetable"
          bordered
          size="default"
          row-key="key"
          :columns="columnApprove"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :show-pagination="true"
          @expand="expand"
        >
          <template slot="serial" slot-scope="text, record, index">{{ index + 1 }}</template>
          <a-spin
            slot="expandedRowRender"
            slot-scope="record"
            :spinning="spinning"
            style="margin: 0"
          >
            <a-table
              bordered
              row-key="id"
              :columns="columnApproveDetail"
              :data-source="record.description"
              :pagination="false"
            />
          </a-spin>
        </s-table>
      </a-tab-pane>
    </a-tabs>
    <a-table
      :pagination="false"
      :columns="tab2.columns"
      :data-source="tab2.tableData"
      row-key="id"
    >
      <template slot="num" slot-scope="text, record, index">{{ index + 1 }}</template>
      <template slot="operation" slot-scope="text, record, index">
        <div class="pub-table-list-action">
          <span @click="handleEdit(record, 3)">查看</span>
        </div>
      </template>
    </a-table>
  </a-modal>
</template>
<script>
import { getCurrentProcess, getFlowChart, getProcessNodeList, getProcInstByBusiness } from '@/api/process'
import { getOrgEmployeesListBy, getProcessGroupPerson } from '@/api/commons'
import { STable } from '@/components'
import JosnBig from 'json-bigint'
import Api from '@/api/material/plan/dailyMaterialRequest.js'

const columnApproveCurrent = [
  {
    title: '序号',
    dataIndex: 'serial',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '流程名称',
    dataIndex: 'taskName'
  },
  {
    title: '处理人',
    dataIndex: 'userName'
  },
  {
     title: '处理结果',
     dataIndex: 'processStatusName',
       width: 120
    },
    {
     title: '审批意见',
     dataIndex: 'opinions',
    scopedSlots: { customRender: 'opinions' },
     width: 200
    },
  {
    title: '开始时间',
    dataIndex: 'createTime'
  },
  {
    title: '滞留时间',
    dataIndex: 'durationInMillis'
  },
  {
    title: '结束时间',
    dataIndex: 'endTime'
  }
]
const columnApprove = [
  {
    title: '序号',
    dataIndex: 'serial',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '流程名称',
    dataIndex: 'name'
  },
  {
    title: '发起人',
    dataIndex: 'userName'
  },
  {
    title: '发起时间',
    dataIndex: 'startTime'
  },
  {
    title: '滞留时间',
    dataIndex: 'durationTime'
  },
  {
    title: '结束时间',
    dataIndex: 'endTime'
  }
]
const columnApproveDetail = [
  {
    title: '审批人',
    dataIndex: 'userName'
  },
  {
    title: '审批时间',
    dataIndex: 'createTime'
  },
  {
    title: '节点名称',
    dataIndex: 'taskName'
  },
  {
    title: '滞留时间',
    dataIndex: 'durationInMillis'
  },
  {
    title: '审批意见',
    dataIndex: 'formData.opinions'
  }
]
export default {
  components: {
    STable
  },
  props: {
    title: {
      type: String,
      default: '历史记录选择'
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    this.columnApprove = columnApprove
    this.columnApproveCurrent = columnApproveCurrent
    this.columnApproveDetail = columnApproveDetail
    return {
      approveInfos: [],
      spinning: false,

      flowChart: '',
      loadDataCurrent: () => {
        return getCurrentProcess(this.id).then((res) => {
          const processData = res.data
          const userIds = []
          const groupList = []
          processData.forEach((item) => {
            userIds.push(item.assignee)
            item.userName = item.userName || ''
            item.endTime = item.endTime || (item.completed !== 2 && '进行中') || ''
            item.durationInMillis = item.durationInMillis || (item.completed !== 2 && '进行中') || ''
            if (item.formData) {
              try {
                const formDataObj = JosnBig.parse(item.formData)
                item.opinions = formDataObj.opinions
                item.auditResult =
                  formDataObj.reject === 'true' ? '审批不通过' : formDataObj.reject === 'false' ? '审批通过' : ''
              } catch (e) {
                console.error(e)
              }
            } else {
              item.opinions = ''
              item.auditResult = ''
            }
            // 如果groupId存在，则需要查询其节点对应的处理人；completed为1时，表示审批已完成
            if (item.groupId && item.completed !== 1) {
              try {
                const groupIdObj = JosnBig.parse(item.groupId)
                groupList.push({ ...groupIdObj, processTaskId: item.taskDefKey })
              } catch (e) {
                console.error(e)
              }
            }

            item.description = []
          })
          // 获取后面节点的处理人列表
          groupList.length &&
          getProcessGroupPerson({
            assignGroup: groupList
          }).then((res) => {
            const targetObj = res.data || {}
            processData.forEach((item) => {
              if (targetObj[item.taskDefKey] && item.groupId && item.completed !== 1) {
                item.userName = targetObj[item.taskDefKey].map((item) => item.name).join('、')
              }
            })
          })
          return getOrgEmployeesListBy({ userIds, delete: true }).then((employees) => {
            this.flowRequesting = false
            processData.forEach((r) => {
              employees.data.some((e) => {
                if (e.userId === r.assignee) {
                  r.userName = e.name
                  return true
                }
              })
            })
            return res
          })
        })
      },
      loadData: (parameter) => {
        parameter.businessId = this.id
        return getProcInstByBusiness(parameter).then((res) => {
          const data = res.data
          const userIds = []
          data.forEach((item) => {
            userIds.push(item.startUser)
            item.endTime = item.endTime || '进行中'
            item.durationTime = item.durationTime || '进行中'
            item.description = []
          })
          return getOrgEmployeesListBy({ userIds }).then((employees) => {
            this.flowRequesting = false
            res.data.forEach((r) => {
              employees.data.some((e) => {
                if (e.startUser === r.userId) {
                  r.userName = e.name
                  return true
                }
              })
            })
            console.log('数据返回对象：', res)
            return res
          })
        })
      },
      type: 0,
      visible: false,
      tab2: {
        pageNo: 1,
        pageSize: 10,
        totalSize: 0,
        tableData: [],
        columns: [
          {
            title: '序号',
            scopedSlots: { customRender: 'num' }
          },
          {
            title: '变更人',
            dataIndex: 'changeUser'
          },
          {
            title: '变更时间',
            dataIndex: 'modifiedTime'
          },
          {
            title: '操作',
            dataIndex: 'operation',
            scopedSlots: { customRender: 'operation' }
          }
        ]
      }
    }
  },
  methods: {
    open(params) {
      this.visible = true
    },
    handleOk() {
      this.visible = false
    },
    tab2list(params) {
      Api.queryByHistory({ id: this.id }).then((res) => {
        this.tab2.tableData = res.data
        this.tab2.totalSize = res.totalElements || res.totalSize
      })
    },
    handleEdit(record, state) {
      this.$bus.$emit('showApprovalDetailsDialog', record.id)
    },
    handleClose() {
      this.$emit('confirm')
    },
    getFlowChart() {
      this.spinning = true
      getFlowChart(this.id)
        .then((res) => {
          this.spinning = false
          console.log(res)
          if (res.code === 200) {
            this.flowChart = 'data:image/png;base64,' + res.data

            console.log(this.flowChart)
          }
        })
        .catch(() => {
          this.spinning = false
        })
    },
    expand(expanded, record) {
      console.log(expanded, record)
      if (expanded) {
        this.getProcessNodes(record.procInstId)
      }
    },
    getProcessNodes(e) {
      console.log(e)
      this.spinning = true
      getProcessNodeList({ procInstId: e, pageNo: 1, pageSize: 100 })
        .then((res) => {
          if (res.code === 200) {
            const data = res.data
            const userIds = data.map((d) => {
              if (d.formData) {
                d.formData = JosnBig.parse(d.formData)
              }
              return d.assignee
            })
            getOrgEmployeesListBy({ userIds })
              .then((employees) => {
                this.spinning = false
                res.data.forEach((r) => {
                  employees.data.some((e) => {
                    if (e.userId === r.assignee) {
                      r.userName = e.name
                      return true
                    }
                  })
                })
                console.log(res.data)
                this.$refs.Approvetable.localDataSource.forEach((i) => {
                  if (i.procInstId == e) {
                    console.log(res.data)
                    i.description = res.data
                    // this.$set(i, 'description', res.data)
                  }
                })
                console.log(this.$refs.Approvetable.localDataSource)
              })
              .catch(() => {
                this.spinning = false
              })
          }
        })
        .catch(() => {
          this.spinning = false
        })
    }
  },
  watch: {
    visible(v) {
      if (v) {
        this.tab2list()
        this.$nextTick(() => {
          console.log(this.$refs)
          if (this.$refs.Approvetable) {
            this.$refs.Approvetable.refresh()
          }
          if (this.$refs.ApprovetableCurrent) {
            this.$refs.ApprovetableCurrent.refresh()
          }
        })
        this.getFlowChart()
      } else {
        this.type = 0
        this.flowChart = ''
        if (this.$refs.Approvetable) {
          this.$refs.Approvetable.localDataSource = []
        }
        if (this.$refs.ApprovetableCurrent) {
          this.$refs.ApprovetableCurrent.localDataSource = []
        }
      }
    }
  }
}
</script>
